package org.chen.global_exception;

import org.chen.exception.CustomException;
import org.chen.result.ResultBody;
import org.chen.service_enum.ErrorCode;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.servlet.NoHandlerFoundException;

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(value = Exception.class)
    public ResultBody<?> handleException(Exception e) {
        if (e instanceof NoHandlerFoundException) {
            return ResultBody.error(ErrorCode.NOT_FOUND);
        } else if (e instanceof MissingServletRequestParameterException) {
            return ResultBody.error(ErrorCode.BAD_REQUEST);
        } else if (e instanceof MethodArgumentNotValidException) {
            return ResultBody.error(ErrorCode.BAD_REQUEST.getCode(),
                    ((MethodArgumentNotValidException) e).getBindingResult().getFieldError().getDefaultMessage());
        } else {
            // Log the exception (optional)
//            return ResultBody.error(ErrorCode.INTERNAL_SERVER_ERROR);
            return ResultBody.error(ErrorCode.INTERNAL_SERVER_ERROR.getCode(), e.getMessage());
        }
    }

    @ExceptionHandler(value = CustomException.class)
    public ResultBody<?> handleCustomException(CustomException e) {
        return ResultBody.error(e.getCode(), e.getMessage());
    }
}
